package com.leyou.common.filter;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.config.FilterProperties;
import com.leyou.common.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
@EnableConfigurationProperties(FilterProperties.class)
public class AuthFilter extends ZuulFilter {
    @Autowired
    private JwtProperties prop;

    @Autowired
    private FilterProperties filterProp;

    /**
     * 过滤器类型 pre前置, post后置
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器的执行顺序
     */
    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER+1;
    }

    /**
     * 是否开启当前过滤器 true开启，false关闭
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器业务
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        //得到request对象
        HttpServletRequest request = ctx.getRequest();
        //得到当前的请求url
        String requestURI = request.getRequestURI();
        //判断当前请求是否在白名单内
        if(isAllowUrl(requestURI)){
            return null;
        }
        //得到token
        String lyToken = CookieUtils.getCookieValue(request, "LY_TOKEN");
        //判断token是否存在
        if(StringUtils.isBlank(lyToken)){
            //阻止当前访问继续
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);
        }
        try {
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(lyToken, prop.getPublicKey(), UserInfo.class);

            //接下来的步骤，其实暂时没有用到
            //获取当前用户的角色信息
            String role = payload.getUserInfo().getRole();
            //把角色信息放到请求头中
            ctx.addZuulRequestHeader("ROLE_HEADER", role);
            ctx.addZuulRequestHeader(prop.getUser().getUserId(), payload.getUserInfo().getId().toString());
        }catch (Exception e){
            //阻止当前访问继续
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);
        }
        //return null表示终止当前方法业务的继续，但是还是会通过网关。
        return null;
    }

    private boolean isAllowUrl(String requestURI) {
        //得到所有的白名单
        List<String> allowPaths = filterProp.getAllowPaths();
        for (String allowPath : allowPaths) {
            if(requestURI.startsWith(allowPath)){
                return true;
            }
        }
        return false;
    }
}
